package com.zb.smbmsc.servlet.user;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import com.zb.smbmsc.pojo.Role;
import com.zb.smbmsc.pojo.User;
import com.zb.smbmsc.service.user.UserService;
import com.zb.smbmsc.service.user.UserServiceImpl;
import com.zb.smbmsc.util.Constants;
import com.zb.smbmsc.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServlet extends HttpServlet {

    UserService userService;

    public UserServlet(){
        userService = new UserServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (!StringUtils.isNullOrEmpty(method)){
            if("savepwd".equals(method)){
                savePwd(req, resp);
            }else if("checkPwd".equals(method)){
                checkPwd(req, resp);
            }else if ("query".equals(method)){
                queryUserList(req, resp);
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    private void savePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object userSession = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");
        if (null != userSession && !StringUtils.isNullOrEmpty(newpassword)){
            boolean flag = userService.updatePwd(((User) userSession).getId(), newpassword);
            if (flag){
                req.setAttribute(Constants.MESSAGE, "密码修改成功，请重新登录！");
                //移除session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else{
                req.setAttribute(Constants.MESSAGE, "密码修改失败，请重试！");
            }
        }else{
            req.setAttribute(Constants.MESSAGE, "session过期或新密码异常，请重试！");
        }

        req.getRequestDispatcher("jsp/pwdmodify.jsp").forward(req, resp);
    }

    private void checkPwd(HttpServletRequest req, HttpServletResponse resp){
        String oldpassword = req.getParameter("oldpassword");
        Object userSession = req.getSession().getAttribute(Constants.USER_SESSION);

        Map<String, Object> resultMap = new HashMap<>();
        if(null == userSession){
            resultMap.put("result", "sessionerror");
        }else{
            if(StringUtils.isNullOrEmpty(oldpassword)){
                resultMap.put("result", "error");
            }else{
                if (oldpassword.equals(((User)userSession).getUserPassword())){
                    resultMap.put("result", "true");
                }else{
                    resultMap.put("result", "false");
                }
            }
        }

        resp.setContentType("application/json");
        try {
            PrintWriter writer = resp.getWriter();
            writer.write(JSON.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void queryUserList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String queryUserName = req.getParameter("queryUserName");
        String queryUserRole = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");

        //查询总数
        int userCount = userService.selectUserCount(queryUserName, queryUserRole);

        int pageSize = 5;
        int currentPageNo = 1;
        PageSupport pageSupport = new PageSupport();
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(userCount);
        if(!StringUtils.isNullOrEmpty(pageIndex)){
            currentPageNo = Integer.parseInt(pageIndex);
        }
        pageSupport.setCurrentPageNo(currentPageNo);
        int totalPageCount = pageSupport.getTotalPageCount();//总页数
        //查询用户列表
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if (currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }
        List<User> userList = userService.selectUserList(queryUserName, queryUserRole, currentPageNo, pageSize);

        //查询角色列表
        List<Role> roleList = userService.getRoleList();

        req.setAttribute("userList", userList);
        req.setAttribute("roleList", roleList);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalCount", userCount);

        System.out.println(req.getContextPath());
        req.getRequestDispatcher("jsp/userlist.jsp").forward(req, resp);
    }
}
